<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header">
        <div class="mb-3">
          <el-tag>{{ textTip }}</el-tag>
        </div>
        <div class="grid grid-cols-3 mb-3">
          <el-button-group>
            <el-button type="success" @click="handleCreate">新增</el-button>
            <el-button type="danger" @click="handleDeleteAll">批量删除</el-button>
            <el-button type="success" @click="allAlterDialog = true">一键修改</el-button>
          </el-button-group>
          <div class="justify-self-center">
            <el-button-group>
              <el-button :type="jackpotType === 2 ? 'primary' : '' " @click="deBounceWrap(getList, 1, 2)">铜盲盒
              </el-button>
              <el-button :type="jackpotType === 1 ? 'primary' : '' " @click="deBounceWrap(getList, 1, 1)">银盲盒
              </el-button>
              <el-button :type="jackpotType === 3 ? 'primary' : '' " @click="deBounceWrap(getList, 1, 3)">金盲盒
              </el-button>
              <el-button :type="jackpotType === 4 ? 'primary' : '' " @click="deBounceWrap(getList, 1, 4)">铜(背包)
              </el-button>
              <el-button :type="jackpotType === 5 ? 'primary' : '' " @click="deBounceWrap(getList, 1, 5)">银(背包)
              </el-button>
              <el-button :type="jackpotType === 6 ? 'primary' : '' " @click="deBounceWrap(getList, 1, 6)">金(背包)
              </el-button>
            </el-button-group>
          </div>
          <div class="justify-self-center">
            <el-button type="success" @click="handleReplacement">更换新奖池</el-button>
          </div>
        </div>
      </div>
      <div class="item">
        <el-table ref="dataList"
                  :data="menuList"
                  @selection-change="handleSelectionChange"
                  row-key="id" border
                  class="w-full mb-3"
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column type="selection"></el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="price" label="价格"></el-table-column>
          <el-table-column prop="picture" label="图片">
            <template slot-scope="scope">
              <el-popover placement="right" max-width="420" trigger="hover">
                <img :src="scope.row.picture" alt="" style="max-width: 200px;max-height: 200px">
                <img slot="reference" :src="scope.row.picture" alt="" style="width: 50px;">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量"></el-table-column>

          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)" plain>编辑
              </el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)" plain>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <cus-pagination
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.perPage"
          @pagination="getList(1,jackpotType)"
        />
      </div>
    </el-card>
    <!-- 删除弹框 -->
    <el-dialog
      title="确定删除吗?"
      :visible.sync="deleteDialogVisible"
      width="435px">
      <span style=""><em style="font-style:normal;color:red">删除后不可恢复</em>，你还要继续吗？</span>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 一键修改  -->
    <el-dialog title="一键修改" :visible.sync="allAlterDialog" width="30%">
      <div>
        <div class="grid grid-cols-3 gap-x-4 mb-2 items-center" v-for="item in menuListLocal" :key="item.gift_id">
          <p>礼物 : {{ item.name }}</p>
          <el-input-number :min="0" v-model="item.quantity"></el-input-number>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="allAlterDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmAllAlter">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新增编辑弹框 -->
    <el-dialog v-dialogDrag :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible"
               @close="handleDialogClose('editRulesForm')">
      <el-form :model="editRulesForm" :rules="editRulesFormRules" ref="editRulesForm" label-width="120px"
               class="demo-ruleForm">
        <el-form-item label="选择礼物" prop="gift_id">
          <el-select filterable v-model="editRulesForm.gift_id">
            <el-option v-for="item in giftList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input v-model.number="editRulesForm.quantity" placeholder="请输入礼物数量"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="submitForm('editRulesForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  listData,
  postAddData,
  putEditData,
  deleteData,
  postGift,
  editMore,
  replacePool
} from '@/api/blindBox/jackpot'

export default {
  data() {
    return {
      confirmBtn: false,

      giftList: [],
      jackpotAction: 1,
      jackpotType: 1,
      row_id: 0,
      // 表单规则
      editRulesFormRules: {
        quantity: [
          {required: true, message: '请输入礼物数量', trigger: 'blur'},
          {type: 'number', min: 1, message: '请输入大于1的数值'}
        ],
        gift_id: [{required: true, message: '请选择礼物', trigger: 'change'}]
      },
      editRulesForm: {
        quantity: undefined,
        gift_id: undefined
      },
      dialogStatus: '',
      // dialog的头部信息
      titleMap: {
        update: '编辑',
        create: '添加'
      },
      dialogFormVisible: false,
      deleteDialogVisible: false,
      /* 一键修改 dialog 开关 */
      allAlterDialog: false,
      listLoading: false,
      menuList: [],
      /* 备份 列表， 用于一键修改展示 */
      menuListLocal: [],
      limitList: [],
      listQuery: {
        page: 1,
        perPage: 10,
      },
      total: 0,
      // 勾选内容
      multipleSelection: [],
      // 要删除的内容的ids
      dataIds: '',
    }
  },
  created() {
    this.getList(1, 1)
    this.getGift()
  },
  computed: {
    textTip() {
      switch (this.jackpotType) {
        case 1:
          return "当前为银盲盒"
        case 2:
          return "当前为铜盲盒"
        case 3:
          return "当前为金盲盒"
        case 4:
          return "当前为铜背包"
        case 5:
          return "当前为银背包"
        case 6:
          return "当前为金背包"
      }
    }
  },
  methods: {
    getList(action, type) {
      this.listLoading = true
      if (this.jackpotType !== type) {
        this.listQuery.page = 1
      }
      this.jackpotType = type

      let params = Object.assign(this.listQuery, {
        action: this.jackpotAction,
        type: this.jackpotType
      })

      listData(params).then(response => {
        this.menuList = response.data.list
        this.menuListLocal = JSON.parse(JSON.stringify(response.data.list))
        this.total = response.data.meta.total
        this.listLoading = false
        this.confirmBtn = false
      })
    },
    /* 置换新奖池 */
    handleReplacement() {
      replacePool(this.jackpotType)
        .then(() => {
          this.$message.success("置换成功")
          this.getList(1, this.jackpotType)
        })
        .catch(() => {
          this.$message.error("置换失败")
        })
    },
    /* 一键修改确认回调 */
    confirmAllAlter() {
      const info = this.menuListLocal.reduce((pre, cur) => {
        pre += `${cur.id},${cur.gift_id},${cur.quantity};`
        return pre
      }, "")
      editMore(1, info).then(() => {
        this.$message.success("修改成功！")
      }).catch(() => {
        this.$message.error("修改失败")
      }).finally(() => {
        this.allAlterDialog = false
        this.getList(1, this.jackpotType)
      })
    },
    getGift() {
      this.giftList = []
      let obj = {
        page: 1,
        perPage: 10000,
        blind_box_type: 8
      }
      postGift(obj).then(response => {
        response.data.list.forEach(item => {
          this.giftList.push({value: item.id, label: item.name})
        })
      })
    },
    // 点击新增
    handleCreate() {
      this.resetForm('editRulesForm')
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    // 点击编辑
    handleUpdate(row) {

      this.row_id = row.id
      this.editRulesForm.quantity = row.quantity;
      this.editRulesForm.gift_id = row.gift_id

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    // 重置表单内容
    resetForm(formName) {
      this.$nextTick(() => {
        // this.$refs[formName].resetFields();
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields();
        }
        this.editRulesForm = {
          user_id: undefined,
          cate_ids: [],
        }
      })
    },
    submitForm(formName) {
      if (this.confirmBtn) return
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmBtn = true

          this.editRulesForm = Object.assign({
            "action": this.jackpotAction,
            "type": this.jackpotType
          }, this.editRulesForm)
          if (this.dialogStatus === 'create') {
            postAddData(this.editRulesForm).then(response => {
              if (response.code === 200) {
                this.dialogFormVisible = false;
                this.getList(1, this.jackpotType)
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                });
              } else {
                this.confirmBtn = false
              }
            })
          } else {
            putEditData(this.row_id, this.editRulesForm).then(response => {
              if (response.code === 200) {
                this.getList(1, this.jackpotType)
                this.dialogFormVisible = false;
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                });
              } else {
                this.confirmBtn = false
              }
            })
          }
        } else {

          return false;
        }
      });
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 点击单个删除
    handleDelete(row) {
      this.dataIds = {ids: `${row.id}`}
      this.deleteDialogVisible = true
    },
    // 点击批量删除
    handleDeleteAll() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请先勾选内容',
          type: 'warning'
        });
        return;
      } else if (this.multipleSelection.length !== 0) {
        let ids = '';
        for (let key in this.multipleSelection) {
          ids += `${this.multipleSelection[key].id},`
        }
        ids = ids.substring(0, ids.length - 1)
        this.dataIds = {ids: ids}
      }
      this.deleteDialogVisible = true
    },
    // 确定删除
    confirmDelete() {
      if (this.confirmBtn) return
      this.confirmBtn = true

      let obj = Object.assign({'action': 1}, this.dataIds)
      deleteData(obj).then((response) => {
        if (response.code === 200) {
          this.getList(1, this.jackpotType)
          this.deleteDialogVisible = false;
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          });
        } else {
          this.confirmBtn = false
        }
      })
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].clearValidate(); // 清除整个表单的校验
      }
    },
  },
}
</script>

<style scoped>

</style>
